package com.zhangshujie.ShoppingSystem;

import java.util.Iterator;
import java.util.List;

public class ProductManager {
    private List<Product> products;
    private FileManager fileManager;

    public ProductManager(FileManager fileManager) {
        this.fileManager = fileManager;
        this.products = fileManager.loadProducts();
    }

    public void listAllProducts() {
        for (Product product : products) {
            System.out.println(product);
        }
    }

    public void addProduct(Product product) {
        products.add(product);
        fileManager.saveProducts(products);
        System.out.println("商品添加成功！");
    }

    public void updateProduct(Product updatedProduct) {
        for (Product product : products) {
            if (product.id.equals(updatedProduct.id)) {
                product.name = updatedProduct.name;
                product.manufacturer = updatedProduct.manufacturer;
                product.productionDate = updatedProduct.productionDate;
                product.model = updatedProduct.model;
                product.purchasePrice = updatedProduct.purchasePrice;
                product.retailPrice = updatedProduct.retailPrice;
                product.quantity = updatedProduct.quantity;
                fileManager.saveProducts(products);
                System.out.println("商品更新成功！");
                return;
            }
        }
        System.out.println("未找到指定ID的商品！");
    }

    public void deleteProduct(String id) {
        Iterator<Product> iterator = products.iterator();
        while (iterator.hasNext()) {
            Product product = iterator.next();
            if (product.id.equals(id)) {
                iterator.remove();
                fileManager.saveProducts(products);
                System.out.println("商品删除成功！");
                return;
            }
        }
        System.out.println("未找到指定ID的商品！");
    }

    public void searchProducts(String name, String manufacturer, Double retailPrice) {
        for (Product product : products) {
            if ((name == null || product.name.contains(name)) &&
                    (manufacturer == null || product.manufacturer.contains(manufacturer)) &&
                    (retailPrice == null || product.retailPrice == retailPrice)) {
                System.out.println(product);
            }
        }
    }

    public Product findProductById(String id) {
        for (Product product : products) {
            if (product.id.equals(id)) {
                return product;
            }
        }
        return null;
    }


}